package site.teamo.biu.net.common.coder;

import com.alibaba.fastjson2.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import site.teamo.biu.net.common.message.Message;

/**
 * @author haocongshun
 * @date 2023/02/10 10:43:27
 */
@Slf4j
public class MessageEncoder extends MessageToByteEncoder<Message> {

    @Getter
    private final String name;

    public MessageEncoder(String name) {
        this.name = name;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        //写入标识位
        out.writeLong(Message.flag);
        byte[] messageBytes = JSON.toJSONBytes(msg);
        //写入数据长度
        out.writeInt(messageBytes.length);
        //写入类型标识
        out.writeInt(msg.type().code);
        //写入数据
        out.writeBytes(messageBytes);
        if (log.isDebugEnabled()) {
            log.info("{} 编码数据: {}Bytes", name, messageBytes.length);
        }
    }
}
